package com.zxp.cloud.zuul.filter;

import cn.hutool.core.util.StrUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shollin
 * @desc
 * @date 2021/8/5/005 7:07
 */
@Component
@Slf4j
public class Oauth2GatewayFilter extends ZuulFilter {

    // 过滤器类型： pre post error  route
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    // 过滤器业务代码 , return null;就表示放行
    @Override
    public Object run() throws ZuulException {

        // 第一步：拿到request reponse对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        final HttpServletResponse response = requestContext.getResponse();

        // 第二步：处理放行的逻辑：去认证、请求头无请求信息
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        String host = request.getRemoteHost();
        log.info("请求URI：{}，HTTP Method：{}，请求IP：{}", requestURI, method, host);

        //获取token
        String authHeader = request.getHeader("Authorization");


        //如果是对授权中心的访问,则全部放过
        if (requestURI.startsWith("/token")) {
            return null;
        }

        if(StrUtil.isBlank(authHeader) || !StrUtil.startWith(authHeader,"bearer ")){ //
            return null;
        }

        // 第三步：检验token


        return null; // yty
    }
}
